import { defineStore } from "pinia";
import { ref } from "vue";
import { clearAuthent, getAuthent, setAuthent } from "@/network/utils";
export default defineStore("baseStore", () => {
  const token = ref<string>(getAuthent("token") || "");
  const menuActive = ref<number>(0);
  const userInfo = ref<Store.BaseStore["userInfo"]>(
    JSON.parse(getAuthent("userInfoCache") || "{}")
  );
  const menuList = ref<TabBar.TabBarItem[]>([
    {
      text: "运单",
      icon: "home-fill",
      path: "/pages/layout/waybill/index",
    },
    {
      text: "下单",
      icon: "shopping-cart-fill",
      path: "/pages/layout/createOrder/index",
    },
    {
      text: "我的",
      icon: "account-fill",
      path: "/pages/layout/my/index",
    },
  ]);
  // 设置选中菜单
  const setActive = (index: number) => {
    menuActive.value = index;
  };
  // 初始化选中菜单
  const initMenuActive = (path: string) => {
    if (!path) return;
    menuActive.value = menuList.value.findIndex(
      (item: TabBar.TabBarItem) => item.path === path
    );
  };
  const logout = () => {
    setToken("");
    setUserInfo({});
    setActive(0);
    clearAuthent();
    uni.reLaunch({
      url: "/pages/login/index",
    });
  };
  const setToken = (val: string) => {
    token.value = val;
    setAuthent("token", val);
  };
  const setUserInfo = (userInfoCache: Store.BaseStore["userInfo"]) => {
    userInfo.value = userInfoCache;
    setAuthent("userInfoCache", JSON.stringify(userInfo.value));
  };
  return {
    token,
    menuActive,
    userInfo,
    menuList,
    setActive,
    initMenuActive,
    logout,
    setUserInfo,
    setToken,
  };
});
